package org.javaforever.cookieshop.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.javaforever.cookieshop.domain.PermissionBean;
import org.javaforever.cookieshop.domain.RoleBean;
import org.javaforever.cookieshop.service.RoleService;
import org.javaforever.cookieshop.serviceimpl.RoleServiceImpl;
import org.javaforever.cookieshop.utils.BooleanUtil;
import org.javaforever.cookieshop.utils.PDFUtil;
import org.javaforever.cookieshop.utils.POIExcelUtil;
import org.javaforever.cookieshop.utils.POIPPTUtil;
import org.javaforever.cookieshop.utils.StringUtil;
import org.javaforever.cookieshop.utils.WordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping(value = "/roleController")
@RestController
public class RoleController {
	public RoleBean tempRole = new RoleBean();
	@Autowired
	protected RoleService service;

	@RequestMapping(value = "/activateAllRoles", method = RequestMethod.POST)
	public Map<String,Object> activateAllRoles(@RequestParam(value = "ids", required = true) String ids) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.activateAllRoles(ids);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/activateRole", method = RequestMethod.POST)
	public Map<String,Object> activateRole(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.activateRole(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/addRole", method = RequestMethod.POST)
	public Map<String,Object> addRole(@RequestBody RoleBean role) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.addRole(role);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/assignPermissionsToRole", method = RequestMethod.POST)
	public Map<String,Object> assignPermissionsToRole(Long roleId,String permissionIds) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        boolean success = service.assignPermissionsToRole(roleId,permissionIds);
        result.put("success",success);
        result.put("rows",null);
        return result;
	}
	@RequestMapping(value = "/checkAccessRole", method = RequestMethod.GET)
	public Map<String,Object> checkAccessRole() throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/cloneAllRoles", method = RequestMethod.POST)
	public Map<String,Object> cloneAllRoles(@RequestParam(value = "ids", required = true) String ids) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.cloneAllRoles(ids);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/cloneRole", method = RequestMethod.POST)
	public Map<String,Object> cloneRole(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.cloneRole(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/deleteAllRoles", method = RequestMethod.POST)
	public Map<String,Object> deleteAllRoles(@RequestParam(value = "ids", required = true) String ids) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.deleteAllRoles(ids);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/deleteRole", method = RequestMethod.POST)
	public Map<String,Object> deleteRole(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.deleteRole(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/exportPPTRoles")
	public void exportPPTRoles(HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception{
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Roles.pptx");
            List<RoleBean> list = service.listAllRoles();
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "角色信息表";
            String [] headers = {"序号","名字","活跃"};
            Boolean [] isImages = {false,false,false};
            
            for (RoleBean role:list) {
                Object [] row = {StringUtil.toNullString(role.getId()),role.getRoleName(),StringUtil.toNullString(role.getActive())};
                contents.add(Arrays.asList(row));
            }
            
            POIPPTUtil.exportPPTWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/exportRoles")
	public void exportRoles(HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception{
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Roles.xls");
            List<RoleBean> list = service.listAllRoles();
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "角色信息表";
            String [] headers = {"序号","名字","活跃"};
            Boolean [] isImages = {false,false,false};
            
            for (RoleBean role:list) {
                Object [] row = {StringUtil.toNullString(role.getId()),role.getRoleName(),StringUtil.toNullString(role.getActive())};
                contents.add(Arrays.asList(row));
            }
            
            POIExcelUtil.exportExcelWorkbookWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/exportRolesPDF")
	public void exportRolesPDF(HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception{
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Roles.pdf");
            List<RoleBean> list = service.listAllRoles();
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "角色信息表";
            String [] headers = {"序号","名字","活跃"};
            Boolean [] isImages = {false,false,false};
            
            for (RoleBean role:list) {
                Object [] row = {StringUtil.toNullString(role.getId()),role.getRoleName(),StringUtil.toNullString(role.getActive())};
                contents.add(Arrays.asList(row));
            }
            
            PDFUtil.exportPDFWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/exportRolesWord")
	public void exportRolesWord(HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception{
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Roles.doc");
            List<RoleBean> list = service.listAllRoles();
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "角色信息表";
            String [] headers = {"序号","名字","活跃"};
            Boolean [] isImages = {false,false,false};
            
            for (RoleBean role:list) {
                Object [] row = {StringUtil.toNullString(role.getId()),role.getRoleName(),StringUtil.toNullString(role.getActive())};
                contents.add(Arrays.asList(row));
            }
            
            WordUtil.exportWordWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/filterPPTRoles", method = RequestMethod.GET)
	public void filterPPTRoles(HttpSession session,HttpServletResponse response,HttpServletRequest request,@RequestParam(value = "roleName", required = false) String roleName,@RequestParam(value = "active", required = false) String active) throws Exception{
        RoleBean role0 = new RoleBean();
        if (!StringUtil.isBlank(roleName)) role0.setRoleName(roleName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) role0.setActive(activeBool);
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Roles.pptx");
            List<RoleBean> list = service.searchRolesByFields(role0);
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "角色信息表";
            String [] headers = {"序号","名字","活跃"};
            Boolean [] isImages = {false,false,false};
            
            for (RoleBean role:list) {
                Object [] row = {StringUtil.toNullString(role.getId()),role.getRoleName(),StringUtil.toNullString(role.getActive())};
                contents.add(Arrays.asList(row));
            }
            
            POIPPTUtil.exportPPTWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/filterRolesExcel", method = RequestMethod.GET)
	public void filterRolesExcel(HttpSession session,HttpServletResponse response,HttpServletRequest request,@RequestParam(value = "roleName", required = false) String roleName,@RequestParam(value = "active", required = false) String active) throws Exception{
        RoleBean role0 = new RoleBean();
        if (!StringUtil.isBlank(roleName)) role0.setRoleName(roleName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) role0.setActive(activeBool);
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Roles.xls");
            List<RoleBean> list = service.searchRolesByFields(role0);
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "角色信息表";
            String [] headers = {"序号","名字","活跃"};
            Boolean [] isImages = {false,false,false};
            
            for (RoleBean role:list) {
                Object [] row = {StringUtil.toNullString(role.getId()),role.getRoleName(),StringUtil.toNullString(role.getActive())};
                contents.add(Arrays.asList(row));
            }
            
            POIExcelUtil.exportExcelWorkbookWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/filterRolesPDF", method = RequestMethod.GET)
	public void filterRolesPDF(HttpSession session,HttpServletResponse response,HttpServletRequest request,@RequestParam(value = "roleName", required = false) String roleName,@RequestParam(value = "active", required = false) String active) throws Exception{
        RoleBean role0 = new RoleBean();
        if (!StringUtil.isBlank(roleName)) role0.setRoleName(roleName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) role0.setActive(activeBool);
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Roles.pdf");
            List<RoleBean> list = service.searchRolesByFields(role0);
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "角色信息表";
            String [] headers = {"序号","名字","活跃"};
            Boolean [] isImages = {false,false,false};
            
            for (RoleBean role:list) {
                Object [] row = {StringUtil.toNullString(role.getId()),role.getRoleName(),StringUtil.toNullString(role.getActive())};
                contents.add(Arrays.asList(row));
            }
            
            PDFUtil.exportPDFWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/filterRolesWord", method = RequestMethod.GET)
	public void filterRolesWord(HttpSession session,HttpServletResponse response,HttpServletRequest request,@RequestParam(value = "roleName", required = false) String roleName,@RequestParam(value = "active", required = false) String active) throws Exception{
        RoleBean role0 = new RoleBean();
        if (!StringUtil.isBlank(roleName)) role0.setRoleName(roleName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) role0.setActive(activeBool);
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Roles.doc");
            List<RoleBean> list = service.searchRolesByFields(role0);
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "角色信息表";
            String [] headers = {"序号","名字","活跃"};
            Boolean [] isImages = {false,false,false};
            
            for (RoleBean role:list) {
                Object [] row = {StringUtil.toNullString(role.getId()),role.getRoleName(),StringUtil.toNullString(role.getActive())};
                contents.add(Arrays.asList(row));
            }
            
            WordUtil.exportWordWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/findRoleById", method = RequestMethod.POST)
	public Map<String,Object> findRoleById(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        RoleBean role = service.findRoleById(id);
        result.put("success",true);
        result.put("data",role);
        return result;
	}
	@RequestMapping(value = "/findRoleByRoleName", method = RequestMethod.POST)
	public Map<String,Object> findRoleByRoleName(@RequestParam(value = "roleName", required = true) String roleName) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        RoleBean role = service.findRoleByRoleName(roleName);
        result.put("success",true);
        result.put("data",role);
        return result;
	}
	@RequestMapping(value = "/listActiveRolePermissionsUsingRoleId", method = RequestMethod.POST)
	public Map<String,Object> listActiveRolePermissionsUsingRoleId(@RequestParam (required = false) Long roleId) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        Set<PermissionBean> set = new TreeSet<PermissionBean>();
        if (roleId!=null) set = service.listActiveRolePermissionsUsingRoleId(roleId);
        result.put("success",true);
        result.put("rows",set);
        return result;
	}
	@RequestMapping(value = "/listActiveRoles", method = RequestMethod.POST)
	public Map<String,Object> listActiveRoles() throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        List<RoleBean> list = service.listActiveRoles();
        result.put("success",true);
        result.put("rows",list);
        return result;
	}
	@RequestMapping(value = "/listAllRoles", method = RequestMethod.POST)
	public Map<String,Object> listAllRoles() throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        List<RoleBean> list = service.listAllRoles();
        result.put("success",true);
        result.put("rows",list);
        return result;
	}
	@RequestMapping(value = "/listAvailableActiveRolePermissionsUsingRoleId", method = RequestMethod.POST)
	public Map<String,Object> listAvailableActiveRolePermissionsUsingRoleId(@RequestParam (required = false) Long roleId) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        Set<PermissionBean> set = new TreeSet<PermissionBean>();
        if (roleId!=null) set = service.listAvailableActiveRolePermissionsUsingRoleId(roleId);
        result.put("success",true);
        result.put("rows",set);
        return result;
	}
	@RequestMapping(value = "/revokePermissionsFromRole", method = RequestMethod.POST)
	public Map<String,Object> revokePermissionsFromRole(Long roleId,String permissionIds) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        boolean success = service.revokePermissionsFromRole(roleId,permissionIds);
        result.put("success",success);
        result.put("rows",null);
        return result;
	}
	@RequestMapping(value = "/searchRolesByFieldsByPage", method = RequestMethod.POST)
	public Map<String,Object> searchRolesByFieldsByPage(@RequestParam(value = "page", required = false) Integer pagenum,@RequestParam(value = "rows", required = false) Integer pagesize,@RequestParam(value = "last", required = false) String lastFlag,@RequestParam(value = "roleName", required = false) String roleName,@RequestParam(value = "active", required = false) String active) throws Exception{
        RoleBean role = new RoleBean();
        if (!StringUtil.isBlank(roleName)) role.setRoleName(roleName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) role.setActive(activeBool);
        if (pagesize==null || pagesize <= 0) pagesize = 10;
        Integer recordCount = service.countSearchRolesByFieldsRecords(role);
        Integer pageCount = (int)Math.ceil((double)recordCount/pagesize);
        if (pageCount <= 1) pageCount = 1;
        if (pagenum==null || pagenum <= 1) pagenum = 1;
        if (pagenum >= pageCount) pagenum = pageCount;
        Boolean lastFlagBool = BooleanUtil.parseBoolean(lastFlag);
        if (lastFlagBool == null) lastFlagBool = false;
        if (lastFlagBool) pagenum = pageCount;
        Map<String,Object> result = new TreeMap<String,Object>();
        List<RoleBean> roleList = service.searchRolesByFieldsByPage(role,pagesize,pagenum);
        result.put("success",true);
        result.put("rows",roleList);
        result.put("total",recordCount);
        result.put("page",pagenum);
        return result;
	}
	@RequestMapping(value = "/softDeleteAllRoles", method = RequestMethod.POST)
	public Map<String,Object> softDeleteAllRoles(@RequestParam(value = "ids", required = true) String ids) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.softDeleteAllRoles(ids);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/softDeleteRole", method = RequestMethod.POST)
	public Map<String,Object> softDeleteRole(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.softDeleteRole(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/toggleOneRole", method = RequestMethod.POST)
	public Map<String,Object> toggleOneRole(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.toggleOneRole(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/toggleRole", method = RequestMethod.POST)
	public Map<String,Object> toggleRole(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.toggleRole(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/updateRole", method = RequestMethod.POST)
	public Map<String,Object> updateRole(@RequestBody RoleBean role) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.updateRole(role);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
}

